/*
 * 2005-12-27 lxm 创建。 
 */
package com.hd123.rumba.organization;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.hibernate.FlushMode;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.type.Type;

import com.hd123.rumba.domain.CDomain;
import com.hd123.rumba.domain.IDomain;
import com.hd123.rumba.domain.IDomainMgr;
import com.hd123.rumba.exception.BusinessException;
import com.hd123.rumba.exception.DuplicateIdException;
import com.hd123.rumba.log.EntityLogger;
import com.hd123.rumba.runtime.IAfterSaveNew;
import com.hd123.rumba.runtime.IBeforeRemove;
import com.hd123.rumba.runtime.IBeforeSave;
import com.hd123.rumba.runtime.Manager;
import com.hd123.rumba.runtime.NamingMgr;
import com.hd123.rumba.runtime.ObserverRegistry;
import com.hd123.rumba.runtime.OperateContext;
import com.hd123.rumba.sql.ResultPage;
import com.hd123.rumba.sql.SCE;
import com.hd123.rumba.sql.SQLSubquery;
import com.hd123.rumba.user.IUser;
import com.hd123.rumba.user.IUserMgr;
import com.hd123.rumba.util.ClassifiedHashtable;
import com.hd123.rumba.util.LevelCode;

/**
 * 组织 | 管理员 | 实现类
 * 
 * @author lxm
 * 
 */
public class OrganizationMgr extends Manager implements IOrganizationMgr {

  public static final String CAPTION_MANAGER = "组织管理员";

  private static final String EVENT_ADDROLETOORGANIZATION = "添加组织角色";
  private static final String EVENT_REMOVEROLEFROMORGANIZATION = "删除组织角色";
  private static final String EVENT_DELETEORGANIZATION = "删除组织";
  private static final String EVENT_UNDELETEORGANIZATION = "恢复组织";

  public OrganizationMgr() {
    super();
    this.registryClass("com.hd123.rumba.organization.IOrganization",
        "com.hd123.rumba.organization.Organization");
  }

  public IOrganization createOrganization() throws BusinessException {
    return new Organization();
  }

  public IOrganization createOrganization(IOrganization upperOrg, String code)
      throws BusinessException, HibernateException {
    checkParameterNotNull(code, "code");
    IOrganization organization = getOrganizationByCode(code);
    if (organization != null)
      throw new DuplicateIdException("已经存在" + COrganization.CAPTION_CODE + "为“" + code + "”的"
          + COrganization.CAPTION_CLASS);
    if (upperOrg != null && COrganization.VALUE_STATE_DELETED.equals(upperOrg.getState()))
      throw new BusinessException("指定的" + COrganization.CAPTION_UPPERORGANIZATION + "的"
          + COrganization.CAPTION_STATE + "为" + COrganization.CAPTION_STATE_DELETED + "，操作被禁止。");

    organization = new Organization();
    IDomainMgr domainMgr = (IDomainMgr) NamingMgr.getInstance().lookupMgr(IDomainMgr.class);
    organization.setDomain(domainMgr.getRootDomain());
    if (upperOrg != null) {
      organization.setUpperOrganization(upperOrg);
    } else {
      organization.setUpperOrganization(null);
    }
    organization.setCode(code);
    organization.setState(COrganization.VALUE_STATE_USING);
    return organization;
  }

  public void addRoleToOrganization(IOrganization organization, IOrgRole role)
      throws BusinessException, HibernateException {
    checkParameterNotNull(organization, "organization");
    checkParameterNotNull(organization, "role");

    if (COrganization.VALUE_STATE_DELETED.equals(organization.getState()))
      throw new BusinessException("指定" + COrganization.CAPTION_CLASS + "的"
          + COrganization.CAPTION_STATE + "为" + COrganization.CAPTION_STATE_DELETED + "，操作被禁止。");

    IOrgRoleMgr roleMgr = null;

    for (int i = 0; i < organization.getOrgRoles().size(); i++) {
      IOrgRole orgRole = (IOrgRole) organization.getOrgRoles().get(i);

      // 该role已经被加入到组织中
      if (role == orgRole)
        return;

      roleMgr = lookupOrgRoleMgr(orgRole);
      if (roleMgr == null)
        throw new BusinessException("意外发现无法识别的" + COrgRole.CAPTION_CLASS + ":" + orgRole.getClass()
            + "。");
      if (roleMgr.canManage(role))
        throw new DuplicateIdException(COrganization.CAPTION_CLASS + "("
            + COrganization.CAPTION_CODE + "='" + organization.getCode() + "')已经存在相同类型的"
            + COrgRole.CAPTION_CLASS + ":" + role.getClassCaption() + "。");
    }

    roleMgr = lookupOrgRoleMgr(role);
    if (roleMgr == null)
      throw new BusinessException("意外发现无法识别的" + COrgRole.CAPTION_CLASS + ":" + role.getClass()
          + "。");
    roleMgr.onBeforeAddOrgRole(organization, role);
    role.setState(COrgRole.VALUE_STATE_USING);
    organization.getOrgRoles().add(role);

    if (organization.getUuid() != null) {
      IUserMgr userMgr = (IUserMgr) NamingMgr.getInstance().lookupMgr(IUserMgr.class);
      IUser operator = userMgr.getSysUser();
      EntityLogger logger = new EntityLogger(this);
      logger.setEntity(organization);
      logger.setEntityConstClass(IOrganization.class);
      logger.setOperator(operator);
      logger.setTime(new Date());
      logger.log(EVENT_ADDROLETOORGANIZATION, organization.getState(), "组织："
          + organization.getNameCode() + "角色：" + role.getClassCaption());
    }
  }

  public void removeRoleFromOrganization(IOrganization organization, IOrgRole role)
      throws BusinessException, HibernateException {
    checkParameterNotNull(organization, "organization");
    checkParameterNotNull(organization, "role");

    if (COrganization.VALUE_STATE_DELETED.equals(organization))
      throw new BusinessException("指定" + COrganization.CAPTION_CLASS + "的"
          + COrganization.CAPTION_STATE + "为" + COrganization.CAPTION_STATE_DELETED + "，操作被禁止。");

    if (organization.getOrgRoles().indexOf(role) < 0)
      return;

    IOrgRoleMgr roleMgr = lookupOrgRoleMgr(role);
    if (roleMgr == null)
      throw new BusinessException("意外发现无法识别的" + COrgRole.CAPTION_CLASS + ":" + role.getClass()
          + "。");

    roleMgr.onBeforeRemoveOrgRole(organization, role);
    organization.getOrgRoles().remove(role);
    getSession().delete(role);

    IUserMgr userMgr = (IUserMgr) NamingMgr.getInstance().lookupMgr(IUserMgr.class);
    IUser operator = userMgr.getSysUser();
    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(organization);
    logger.setEntityConstClass(IOrganization.class);
    logger.setOperator(operator);
    logger.setTime(new Date());
    logger.log(EVENT_REMOVEROLEFROMORGANIZATION, organization.getState(), organization
        .getCodeName());
  }

  public ClassifiedHashtable verifyOrganization(IOrganization organization, boolean withWarn)
      throws BusinessException, HibernateException {
    ClassifiedHashtable h = new ClassifiedHashtable();

    if (organization.getCode() == null)
      h.putMessage("code", ClassifiedHashtable.ERROR, COrganization.CAPTION_CLASS + "的"
          + COrganization.CAPTION_CODE + "不能为空。");

    if (organization.getCode() != null) {
      IOrganization org = getOrganizationByCode(organization.getCode());
      if (org != null && !org.getUuid().equals(organization.getUuid()))
        h.putMessage("code", ClassifiedHashtable.ERROR, "已经存在相同" + COrganization.CAPTION_CODE + "的"
            + COrganization.CAPTION_CLASS + "。");
    }

    if (withWarn && organization.getOrgRoles().size() == 0)
      h.putMessage("orgRoles", ClassifiedHashtable.WARN, COrganization.CAPTION_CLASS + "("
          + COrganization.CAPTION_CODE + "='" + organization.getCode() + "')没有定义任何"
          + COrgRole.CAPTION_CLASS + "。");

    autoSyncOrgDomain(organization);

    if (h.size() > 0)
      return h;
    else
      return null;
  }

  /** @deprecated */
  public void saveOrganization(IOrganization organization, Integer toState, IUser operator, long oca)
      throws BusinessException, HibernateException {
    this.doSaveOrganization(organization, new OperateContext(operator));
  }

  public void saveOrganization(IOrganization organization, OperateContext operate)
      throws BusinessException, HibernateException {
    this.doSaveOrganization(organization, operate);
  }

  /** @deprecated */
  public void saveOrganization(IOrganization organization, IUser operator)
      throws BusinessException, HibernateException {
    this.doSaveOrganization(organization, new OperateContext(operator));
  }

  private void doSaveOrganization(IOrganization organization, OperateContext operate)
      throws BusinessException, HibernateException {
    checkParameterNotNull(organization, "organization");
    checkParameterNotNull(operate, "operate");

    ClassifiedHashtable h = this.verifyOrganization(organization, false);
    if (h != null && h.size() > 0)
      throw new BusinessException(h.getAllMessages());

    Date operTime = operate.getTime();
    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(organization);
    logger.setEntityConstClass(COrganization.class);
    logger.setOperator(operate.getOperator());
    logger.setTime(operTime);
    Boolean isNew = Boolean.FALSE;

    // 保存组织域
    IDomainMgr domainMgr = (IDomainMgr) NamingMgr.getInstance().lookupMgr(IDomainMgr.class);
    organization.getOrganizationDomain().setLastModified(operTime);
    organization.getOrganizationDomain().setLastModifier(operate.getOperator().getCodeName());
    domainMgr.saveDomain(organization.getOrganizationDomain(), operate, organization
        .getOrganizationDomain().getOca());

    ObserverRegistry.notifyObservers(IBeforeSave.class, organization);

    organization.setLastModified(operTime);
    organization.setLastModifier(operate.getOperator().getCodeName());
    updateOrganizationLevelId(organization);
    for (int i = 0; i < organization.getOrgRoles().size(); i++) {
      IOrgRole orgRole = (IOrgRole) organization.getOrgRoles().get(i);
      IOrgRoleMgr roleMgr = lookupOrgRoleMgr(orgRole);
      roleMgr.onBeforeSaveOrg(orgRole, operate);
    }

    if (organization.getUuid() == null)
      isNew = Boolean.TRUE;
    getSession().saveOrUpdate(organization);

    for (int i = 0; i < organization.getOrgRoles().size(); i++) {
      IOrgRole orgRole = (IOrgRole) organization.getOrgRoles().get(i);
      IOrgRoleMgr roleMgr = lookupOrgRoleMgr(orgRole);
      roleMgr.onAfterSaveOrg(orgRole, operate);
    }

    if (isNew.booleanValue())
      ObserverRegistry.notifyObservers(IAfterSaveNew.class, organization);

    if (isNew.booleanValue())
      logger.log(EntityLogger.EVENT_ADDNEW, organization.getState(), null);
    else
      logger.log(EntityLogger.EVENT_MODIFY, organization.getState(), null);
  }

  /** @deprecated */
  public void deleteOrganization(IOrganization organization, IUser operator)
      throws BusinessException, HibernateException {
    this.deleteOrganization(organization, new OperateContext(operator));
  }

  public void deleteOrganization(IOrganization organization, OperateContext operate)
      throws BusinessException, HibernateException {
    this.checkParameterNotNull(organization, "organization");
    this.checkParameterNotNull(operate, "operate");

    verifyToDelete(organization);

    Date operTime = operate.getTime();
    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(organization);
    logger.setEntityConstClass(COrganization.class);
    logger.setOperator(operate.getOperator());
    logger.setTime(operTime);

    organization.setState(COrganization.VALUE_STATE_DELETED);
    organization.getOrganizationDomain().setState(CDomain.VALUE_STATE_DELETED);
    ObserverRegistry.notifyObservers(IBeforeRemove.class, organization);
    for (int i = 0; i < organization.getOrgRoles().size(); i++) {
      IOrgRole orgRole = (IOrgRole) organization.getOrgRoles().get(i);
      IOrgRoleMgr roleMgr = lookupOrgRoleMgr(orgRole);
      roleMgr.onDeleteOrg(orgRole, operate);
    }

    organization.setLastModified(operTime);
    organization.setLastModifier(operate.getOperator().getCodeName());
    getSession().saveOrUpdate(organization);

    logger.log(EVENT_DELETEORGANIZATION, organization.getState(), organization.getCodeName());
  }

  /** @deprecated */
  public void undeleteOrganization(IOrganization organization, IUser operator)
      throws BusinessException, HibernateException {
    this.undeleteOrganization(organization, new OperateContext(operator));
  }

  public void undeleteOrganization(IOrganization organization, OperateContext operate)
      throws BusinessException, HibernateException {
    this.checkParameterNotNull(organization, "organization");
    this.checkParameterNotNull(operate, "operate");

    verifyToUndelete(organization);

    Date operTime = operate.getTime();
    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(organization);
    logger.setEntityConstClass(COrganization.class);
    logger.setOperator(operate.getOperator());
    logger.setTime(operTime);

    organization.setState(COrganization.VALUE_STATE_USING);
    organization.getOrganizationDomain().setState(CDomain.VALUE_STATE_NORMAL);
    for (int i = 0; i < organization.getOrgRoles().size(); i++) {
      IOrgRole orgRole = (IOrgRole) organization.getOrgRoles().get(i);
      IOrgRoleMgr roleMgr = lookupOrgRoleMgr(orgRole);
      roleMgr.onUndeleteOrg(orgRole, operate);
    }

    organization.setLastModified(operTime);
    organization.setLastModifier(operate.getOperator().getCodeName());
    getSession().saveOrUpdate(organization);

    logger.log(EVENT_UNDELETEORGANIZATION, organization.getState(), organization.getCodeName());
  }

  public void removeOrganization(IOrganization organization) throws BusinessException,
      HibernateException {
    checkParameterNotNull(organization, "organization");

    for (int i = 0; i < organization.getOrgRoles().size(); i++) {
      IOrgRole orgRole = (IOrgRole) organization.getOrgRoles().get(i);
      IOrgRoleMgr roleMgr = lookupOrgRoleMgr(orgRole);
      roleMgr.onBeforeRemoveOrg(orgRole);
    }

    ObserverRegistry.notifyObservers(IBeforeRemove.class, organization);
    getSession().delete(organization);

    // 删除组织域
    IDomainMgr domainMgr = (IDomainMgr) NamingMgr.getInstance().lookupMgr(IDomainMgr.class);
    domainMgr.removeDomain(organization.getOrganizationDomain());
  }

  public void registerOrgRoleMgr(Class roleMgrIntf) throws BusinessException {
    checkParameterNotNull(roleMgrIntf, "roleMgrIntf");
    roleMgrRegistry.add(roleMgrIntf);
  }

  public void clearOrgRoleMgrRegistry() {
    roleMgrRegistry.clear();
  }

  public IOrgRoleMgr lookupOrgRoleMgr(String intfMgrName) {
    IOrgRoleMgr roleMgr = null;
    try {
      for (int i = 0; i < roleMgrRegistry.size(); i++) {
        Class roleMgrClass = (Class) roleMgrRegistry.get(i);
        if (roleMgrClass.getName().equals(intfMgrName)) {
          roleMgr = (IOrgRoleMgr) NamingMgr.getInstance().lookupMgr(roleMgrClass);
          break;
        }
      }
      return roleMgr;
    } catch (BusinessException e) {
      return null;
    }
  }

  public IOrgRoleMgr lookupOrgRoleMgr(IOrgRole orgRole) throws BusinessException {
    IOrgRoleMgr roleMgr = null;
    for (int i = 0; i < roleMgrRegistry.size(); i++) {
      Class roleMgrClass = (Class) roleMgrRegistry.get(i);
      IOrgRoleMgr roleMgr2 = (IOrgRoleMgr) NamingMgr.getInstance().lookupMgr(roleMgrClass);
      if (roleMgr2.canManage(orgRole)) {
        roleMgr = roleMgr2;
        break;
      }
    }
    return roleMgr;
  }

  public List getValidOrgRoleMgrList() throws BusinessException {
    return roleMgrRegistry;
  }

  public IOrganization getOrganization(String uuid) throws BusinessException, HibernateException {
    checkParameterNotNull(uuid, "uuid");
    return (IOrganization) getSession().get(IOrganization.class, uuid);
  }

  public IOrganization getOrganizationByCode(String code) throws BusinessException,
      HibernateException {
    checkParameterNotNull(code, "code");
    List list = getSession().find("from Organization o where o.code = ? and o.state <> ?",
        new Object[] {
            code, COrganization.VALUE_STATE_DELETED }, new Type[] {
            Hibernate.STRING, Hibernate.INTEGER });
    if (list.size() > 0)
      return (IOrganization) list.get(0);
    else
      return null;
  }

  public IOrganization getOrganizationByCode(String code, Integer[] states)
      throws BusinessException, HibernateException {
    checkParameterNotNull(code, "code");
    SQLSubquery sq = new SQLSubquery();
    sq.addSelect("o");
    sq.addFrom("Organization", "o");
    SCE cond = new SCE(SCE.VALUE_OPERATOR_AND);
    cond.append(SCE.cond("o.code = ?", code));
    if (states != null)
      cond.append(SCE.cond("o.state in ?", states));
    sq.setWhere(cond);
    ResultPage rp = ResultPage.createHibernateResultPage(getSession(), sq, 0, 0);
    List list = rp.getContentList();
    if (list.size() > 0)
      return (IOrganization) list.get(0);
    else
      return null;
  }

  public IOrganization getOrganizationByOrgDomain(String orgDomainUuid) throws BusinessException,
      HibernateException {
    checkParameterNotNull(orgDomainUuid, "domain");
    List list = getSession().find("from Organization o where o.organizationDomain.uuid = ?",
        orgDomainUuid, Hibernate.STRING);
    if (list.size() > 0)
      return (IOrganization) list.get(0);
    else
      return null;
  }

  public ResultPage getTopOrganizations(int pageSize, int page) throws BusinessException,
      HibernateException {
    SQLSubquery sq = new SQLSubquery();
    sq.addSelect("o");
    sq.addFrom("Organization o");
    sq.addWhere("o.upperOrganization is null");
    sq.addWhere("and o.state <> ?", COrganization.VALUE_STATE_DELETED);
    sq.addOrder("o.code");
    return ResultPage.createHibernateResultPage(getSession(), sq, pageSize, page);
  }

  public ResultPage getLowerOrganizations(IOrganization parentOrg, int pageSize, int page)
      throws BusinessException, HibernateException {
    checkParameterNotNull(parentOrg, "parentOrg");
    SQLSubquery sq = new SQLSubquery();
    sq.addSelect("o");
    sq.addFrom("IOrganization o");
    sq.addWhere("o.upperOrganization.uuid = ?", parentOrg.getUuid());
    sq.addWhere("and o.state <> ?", COrganization.VALUE_STATE_DELETED);
    sq.addOrder("o.code");
    return ResultPage.createHibernateResultPage(getSession(), sq, pageSize, page);
  }

  /** 组织角色管理员（接口）注册表 */
  private List roleMgrRegistry = new ArrayList();

  /**
   * 根据规则修改指定组织的层级码。
   * 
   * @param organization
   *            被修改的组织。
   * @throws BusinessException
   * @throws HibernateException
   */
  private void updateOrganizationLevelId(IOrganization organization) throws BusinessException,
      HibernateException {
    LevelCode lc = new LevelCode(COrganization.VALUE_LEVELIDRULE);
    String levelId = organization.getLevelId();
    if (organization.getUpperOrganization() == null) {
      // 顶级组织
      if (levelId == null || lc.getLevel(levelId) != 0) {
        levelId = createLevelId(organization, lc, null);
        organization.setLevelId(levelId);
      }
    } else {
      // 下级组织
      IOrganization upperOrg = organization.getUpperOrganization();
      if (upperOrg == null) {
        upperOrg = getOrganizationByOrgDomain(organization.getDomain().getUuid());
        organization.setUpperOrganization(upperOrg);
      }
      if (levelId == null || !upperOrg.getLevelId().equals(lc.getParent(levelId))) {
        levelId = createLevelId(organization, lc, upperOrg.getLevelId());
        organization.setLevelId(levelId);
      }
    }

    // TODO 修改所有下级组织的层级码。
  }

  /**
   * 产生一个新的层级码。
   * 
   * @param organization
   * @param lc
   * @param parentLevelId
   *            null表示生成第0级的levelId
   * @return
   * @throws BusinessException
   * @throws HibernateException
   */
  private String createLevelId(IOrganization organization, LevelCode lc, String parentLevelId)
      throws BusinessException, HibernateException {
    String pattern = lc.getSubLevelIdPattern(parentLevelId);
    List list = getSession().find(
        "select o.levelId from Organization o" + " where o.domain.uuid = ? and o.levelId like ?",
        new Object[] {
            organization.getDomain().getUuid(), pattern }, new Type[] {
            Hibernate.STRING, Hibernate.STRING });
    return lc.createSubLevelId(parentLevelId, list);
  }

  /**
   * 为指定组织自动创建并同步组织域。
   * 
   * @param organization
   * @throws BusinessException
   * @throws HibernateException
   */
  private void autoSyncOrgDomain(IOrganization organization) throws BusinessException,
      HibernateException {
    IDomain orgDomain = organization.getOrganizationDomain();
    if (orgDomain == null) {
      // 自动创建组织域
      IDomainMgr domainMgr = (IDomainMgr) NamingMgr.getInstance().lookupMgr(IDomainMgr.class);
      orgDomain = domainMgr.createDomain(organization.getDomain(), organization.getCode(),
          organization.getName());
      if (organization.getUpperOrganization() != null)
        orgDomain.setUpperDomain(organization.getUpperOrganization().getOrganizationDomain());
      else
        orgDomain.setUpperDomain(domainMgr.getRootDomain());

      // 自动创建的orgDomain始终isInternal()=true，以产生正确的LevelId。
      orgDomain.setIsStore(Boolean.TRUE);

      organization.setOrganizationDomain(orgDomain);
    } else {
      orgDomain.setCode(organization.getCode());
      orgDomain.setName(organization.getName());
    }
  }

  public List getLowerOrganizations(IOrganization parentOrg) throws BusinessException,
      HibernateException {
    if (parentOrg != null)
      return getSession().find(
          "from IOrganization o where o.upperOrganization.uuid = ? and o.state <> "
              + COrganization.VALUE_STATE_DELETED + " order by o.code", parentOrg.getUuid(),
          Hibernate.STRING);
    else
      return getSession().find(
          "from " + IOrganization.class.getName()
              + " o where o.upperOrganization is null and o.state <> ? order by o.code",
          COrganization.VALUE_STATE_DELETED, Hibernate.INTEGER);
  }

  @SuppressWarnings("unchecked")
  public List<IOrganization> getAllLowerOrganizations(IOrganization parentOrg)
      throws BusinessException, HibernateException {
    if (parentOrg != null)
      return (List<IOrganization>) getSession().find(
          "from " + IOrganization.class.getName() + " o where o.levelId like ? and o.state <> ?",
          new Object[] {
              parentOrg.getLevelId() + "_%", COrganization.VALUE_STATE_DELETED }, new Type[] {
              Hibernate.STRING, Hibernate.INTEGER });
    else
      return (List<IOrganization>) getSession().find(
          "from " + IOrganization.class.getName() + " o where o.state <> ?",
          COrganization.VALUE_STATE_DELETED, Hibernate.INTEGER);
  }

  public IOrganization getTopOrganization(IOrganization org) throws BusinessException {
    checkParameterNotNull(org, "org");
    IOrganization retOrg = org;
    while (retOrg.getUpperOrganization() != null) {
      retOrg = retOrg.getUpperOrganization();
    }
    return retOrg;
  }

  private void verifyToDelete(IOrganization organization) throws BusinessException,
      HibernateException {
    List list = getSession().find(
        "select count(o) from " + IOrganization.class.getName() + " o"
            + " where o.upperOrganization.uuid = ? and o.state != ?", new Object[] {
            organization.getUuid(), COrganization.VALUE_STATE_DELETED }, new Type[] {
            Hibernate.STRING, Hibernate.INTEGER });
    if (list.size() > 0 && ((Integer) list.get(0)).intValue() > 0)
      throw new BusinessException("指定" + COrganization.CAPTION_CLASS + " "
          + organization.getNameCode() + " 具有可用的下级" + COrganization.CAPTION_CLASS + "，删除操作被禁止。");
  }

  private void verifyToUndelete(IOrganization organization) throws BusinessException,
      HibernateException {
    if (COrganization.VALUE_STATE_DELETED.equals(organization)) {
      getSession().setFlushMode(FlushMode.COMMIT);
      IDomain domain = organization.getDomain();
      IOrganization org2 = this.getOrganizationByCode(organization.getCode());
      if (org2 != null)
        throw new BusinessException(CDomain.CAPTION_CLASS + " " + domain.getNameCode() + " 已经存在相同"
            + COrganization.CAPTION_CODE + "\"" + organization.getCode() + "\"的"
            + COrganization.CAPTION_CLASS + "，恢复删除操作被禁止。");
    }
  }
}
